<template>
  <view class="pickup-create">
    <scroll-view scroll-y class="content">
      <!-- 取件信息 -->
      <view class="section">
        <view class="section-title">📍 取件信息</view>
        <view class="form-item">
          <input 
            v-model="formData.pickupAddress" 
            placeholder="请输入取件地址"
            placeholder-class="placeholder"
          />
        </view>
         <!-- 取快递服务：多图片上传方式 -->
         <view v-if="categoryInfo.serviceType === 2" class="express-upload-section">
           <!-- 快递单号截图（多张） -->
           <view class="form-item">
             <MultiImageUploader
               :images="expressImages"
               title="快递单号截图"
               tip="可上传多张快递单号截图，支持新老食堂混合代取"
               :max-count="9"
               module="order/express/number"
               @update:images="updateExpressImages"
               @upload-success="handleExpressUploadSuccess"
               @upload-error="handleExpressUploadError"
             />
           </view>
           
           <!-- 身份码截图（多张） -->
           <view class="form-item">
             <MultiImageUploader
               :images="identityImages"
               title="身份码截图"
               tip="可上传多张身份码截图，确保信息清晰"
               :max-count="9"
               module="order/express/identity"
               @update:images="updateIdentityImages"
               @upload-success="handleIdentityUploadSuccess"
               @upload-error="handleIdentityUploadError"
             />
           </view>
         </view>
         
         <!-- 其他代取服务：多图片上传方式 -->
         <view v-else-if="categoryInfo.serviceType" class="other-service-upload">
           <!-- 订单截图（多张） -->
           <view class="form-item">
             <MultiImageUploader
               :images="orderImages"
               :title="getOrderImagesTitle()"
               :tip="getOrderImagesTip()"
               :max-count="9"
               module="order/takeout/order"
               @update:images="updateOrderImages"
               @upload-success="handleOrderUploadSuccess"
               @upload-error="handleOrderUploadError"
             />
           </view>
           
           <!-- 取餐码截图（多张） -->
           <view class="form-item">
             <MultiImageUploader
               :images="pickupCodeImages"
               title="取餐码截图"
               :tip="getPickupCodeImagesTip()"
               :max-count="9"
               module="order/takeout/code"
               @update:images="updatePickupCodeImages"
               @upload-success="handlePickupCodeUploadSuccess"
               @upload-error="handlePickupCodeUploadError"
             />
           </view>
         </view>
        <view class="form-item">
          <textarea 
            v-model="formData.pickupRemark" 
            placeholder="取件备注（选填）"
            placeholder-class="placeholder"
            maxlength="200"
          />
        </view>
      </view>

      <!-- 收货信息 -->
      <view class="section">
        <view class="section-title">📦 收货信息</view>
        
        <!-- 地址选择 -->
        <view class="address-selector" @click="selectAddress">
          <view class="address-content" v-if="selectedAddress">
            <view class="address-header">
              <text class="receiver-name">{{ selectedAddress.contactName }}</text>
              <text class="receiver-phone">{{ selectedAddress.contactPhone }}</text>
              <text class="selected-badge">已选中</text>
            </view>
            <view class="address-detail">
              <text class="address-icon">📍</text>
              <text class="address-text">{{ formatAddress(selectedAddress) }}</text>
            </view>
          </view>
          <view class="address-empty" v-else>
            <text class="empty-icon">📍</text>
            <text class="empty-text">点击选择收货地址</text>
          </view>
          <text class="arrow-icon">›</text>
        </view>
        
        <!-- 送达备注 -->
        <view class="form-item">
          <textarea 
            v-model="formData.deliveryRemark" 
            placeholder="送达备注（选填）"
            placeholder-class="placeholder"
            maxlength="200"
          />
        </view>
      </view>

      <!-- 服务费用 -->
      <view class="section">
        <view class="section-title">💰 服务费用</view>
        <view class="fee-input">
          <text>建议: ¥{{ categoryInfo.basePrice }}</text>
          <view class="input-wrapper">
            <text>¥</text>
            <input 
              v-model.number="formData.serviceFee" 
              type="digit"
              placeholder="请输入金额"
            />
          </view>
        </view>
        <view class="fee-tip">
          <text class="tip-icon">💡</text>
          <text class="tip-text">费用越高，接单越快哦~</text>
        </view>
      </view>
    </scroll-view>

    <!-- 底部按钮 -->
    <view class="footer">
      <button class="submit-btn" @click="handleSubmit">
        立即发布 ¥{{ formData.serviceFee || 0 }}
      </button>
    </view>
  </view>
</template>

<script>
import { createPickupOrder, getCategoryList } from '@/api/pickup'
import { getAddressList } from '@/api/address'
import MultiImageUploader from '@/components/MultiImageUploader.vue'

export default {
  components: {
    MultiImageUploader
  },
  data() {
    return {
      categoryId: '',
      categoryInfo: {},
      selectedAddress: null, // 选中的收货地址
      platformFeeRate: 0.25, // 平台服务费率(小数)，将从配置载入，默认25%
      formData: {
        categoryId: '',
        pickupAddress: '',
        pickupCode: '',
        pickupRemark: '',
        deliveryAddress: '',
        receiverName: '',
        receiverPhone: '',
        deliveryRemark: '',
        serviceFee: 0,
        firstImage: '',  // 图片数据的JSON字符串
        secondImage: ''  // 图片数据的JSON字符串
      },
      // 多图片数据
      expressImages: [],     // 快递单号截图（取快递专用）
      identityImages: [],    // 身份码截图（取快递专用）
      orderImages: [],       // 订单截图（取外卖/代取奶咖）
      pickupCodeImages: []   // 取餐码截图（取外卖/代取奶咖）
    }
  },
  computed: {
    // 平台服务费（不在页面显示）
    platformFee() {
      return (this.formData.serviceFee * this.platformFeeRate).toFixed(2)
    },
    // 接单方收益（不在页面显示）
    riderEarning() {
      return (this.formData.serviceFee - this.platformFee).toFixed(2)
    }
  },
  onLoad(options) {
    if (options && options.categoryId) {
      this.categoryId = options.categoryId
      this.formData.categoryId = options.categoryId
    }

    this.loadPlatformFeeRate()
    this.loadCategoryInfo()
    this.loadDefaultAddress()
  },
  onShow() {
    // 从地址选择页返回时，更新收货信息
    if (this.selectedAddress) {
      this.updateDeliveryInfo()
    }
  },
  methods: {
    async loadPlatformFeeRate() {
      try {
        const { getConfig } = require('@/api/config')
        const val = await getConfig('pickup_platform_fee_rate')
        const percent = parseFloat(val)
        if (!isNaN(percent) && percent >= 0 && percent <= 100) {
          this.platformFeeRate = +(percent / 100).toFixed(4)
        } else {
          this.platformFeeRate = 0.25
        }
      } catch (e) {
        this.platformFeeRate = 0.25
      }
    },
    // 加载分类信息
    async loadCategoryInfo() {
      try {
        const categoryList = await getCategoryList()
        this.categoryInfo = categoryList.find(item => String(item.id) === String(this.categoryId)) || {}
        this.formData.serviceFee = this.categoryInfo.basePrice || 0
        
        // 设置导航栏标题
        uni.setNavigationBarTitle({
          title: `发布【${this.categoryInfo.name}】`
        })
      } catch (error) {
        console.error('加载分类信息失败:', error)
        uni.showToast({ title: '加载分类信息失败', icon: 'none' })
      }
    },

    // 加载默认地址
    async loadDefaultAddress() {
      try {
        const list = await getAddressList()
        
        // 查找默认地址
        const defaultAddress = list.find(item => item.isDefault === 1)
        if (defaultAddress) {
          this.selectedAddress = defaultAddress
          this.updateDeliveryInfo()
        } else if (list.length > 0) {
          // 没有默认地址，使用第一个
          this.selectedAddress = list[0]
          this.updateDeliveryInfo()
        }
      } catch (error) {
        console.error('加载地址失败:', error)
      }
    },

    // 选择地址
    selectAddress() {
      uni.navigateTo({
        url: '/pages/address/list?select=true'
      })
    },

    // 格式化地址
    formatAddress(item) {
      let address = ''
      if (item.building) address += item.building
      if (item.room) address += (address ? '-' : '') + item.room
      if (item.detail) address += (address ? ' ' : '') + item.detail
      return address || '暂无详细地址'
    },

    // 更新收货信息
    updateDeliveryInfo() {
      if (this.selectedAddress) {
        this.formData.deliveryAddress = this.formatAddress(this.selectedAddress)
        this.formData.receiverName = this.selectedAddress.contactName
        this.formData.receiverPhone = this.selectedAddress.contactPhone
      }
    },

     // 获取订单截图标题
     getOrderImagesTitle() {
       switch (this.categoryInfo.serviceType) {
         case 3: return '外卖订单截图'
         case 4: return '奶咖订单截图'
         default: return '订单截图'
       }
     },

     // 获取订单截图提示
     getOrderImagesTip() {
       switch (this.categoryInfo.serviceType) {
         case 3: return '可上传多张外卖订单截图，需露出商家名称和位置'
         case 4: return '可上传多张奶咖订单截图，需露出店铺名称和位置'
         default: return '可上传多张订单截图'
       }
     },

     // 获取取餐码截图提示
     getPickupCodeImagesTip() {
       switch (this.categoryInfo.serviceType) {
         case 3: return '可上传多张取餐码截图，确保信息清晰'
         case 4: return '可上传多张取餐码截图，确保信息清晰'
         default: return '可上传多张取餐码截图'
       }
     },

     // 更新快递单号图片
     updateExpressImages(images) {
       this.expressImages = images
     },

     // 更新身份码图片
     updateIdentityImages(images) {
       this.identityImages = images
     },

     // 更新订单截图
     updateOrderImages(images) {
       this.orderImages = images
     },

     // 更新取餐码截图
     updatePickupCodeImages(images) {
       this.pickupCodeImages = images
     },

     // 处理快递单号上传成功
     handleExpressUploadSuccess(event) {
       //console.log('快递单号上传成功:', event)
     },

     // 处理快递单号上传失败
     handleExpressUploadError(event) {
       console.error('快递单号上传失败:', event.error)
     },

     // 处理身份码上传成功
     handleIdentityUploadSuccess(event) {
       //console.log('身份码上传成功:', event)
     },

     // 处理身份码上传失败
     handleIdentityUploadError(event) {
       console.error('身份码上传失败:', event.error)
     },

     // 处理订单截图上传成功
     handleOrderUploadSuccess(event) {
       //console.log('订单截图上传成功:', event)
     },

     // 处理订单截图上传失败
     handleOrderUploadError(event) {
       console.error('订单截图上传失败:', event.error)
     },

     // 处理取餐码截图上传成功
     handlePickupCodeUploadSuccess(event) {
       //console.log('取餐码截图上传成功:', event)
     },

     // 处理取餐码截图上传失败
     handlePickupCodeUploadError(event) {
       console.error('取餐码截图上传失败:', event.error)
     },


    // 校验表单
    validateForm() {
      if (!this.formData.pickupAddress) {
        uni.showToast({ title: '请输入取件地址', icon: 'none' })
        return false
      }
      if (!this.selectedAddress) {
        uni.showToast({ title: '请选择收货地址', icon: 'none' })
        return false
      }
      
      // 图片上传验证
      if (this.categoryInfo.serviceType === 2) {
        // 取快递服务：需要至少一张快递单号截图和一张身份码截图
        if (this.expressImages.length === 0) {
          uni.showToast({ title: '请至少上传一张快递单号截图', icon: 'none' })
          return false
        }
        if (this.identityImages.length === 0) {
          uni.showToast({ title: '请至少上传一张身份码截图', icon: 'none' })
          return false
        }
      } else if (this.categoryInfo.serviceType) {
        // 其他代取服务：需要至少一张订单截图和一张取餐码截图
        if (this.orderImages.length === 0) {
          uni.showToast({ title: '请至少上传一张订单截图', icon: 'none' })
          return false
        }
        if (this.pickupCodeImages.length === 0) {
          uni.showToast({ title: '请至少上传一张取餐码截图', icon: 'none' })
          return false
        }
      }
      
      if (this.formData.serviceFee < this.categoryInfo.basePrice) {
        uni.showToast({ title: `服务费不能低于¥${this.categoryInfo.basePrice}`, icon: 'none' })
        return false
      }
      return true
    },

     // 提交订单
     async handleSubmit() {
       if (!this.validateForm()) return

       try {
         uni.showLoading({ title: '创建订单中...' })
         
         // 准备提交数据
         const submitData = { ...this.formData }
         
         // 根据服务类型处理图片数据
         if (this.categoryInfo.serviceType === 2) {
           // 取快递服务：firstImage是快递单号数组，secondImage是身份码数组
           submitData.firstImage = JSON.stringify(this.expressImages)
           submitData.secondImage = JSON.stringify(this.identityImages)
         } else if (this.categoryInfo.serviceType) {
           // 其他代取服务：firstImage是订单截图数组，secondImage是取餐码截图数组
           submitData.firstImage = JSON.stringify(this.orderImages)
           submitData.secondImage = JSON.stringify(this.pickupCodeImages)
         }
         
         const res = await createPickupOrder(submitData)
         uni.hideLoading()
         
         uni.showToast({ title: '订单创建成功', icon: 'success' })
         
         // 跳转到订单详情或我的发布页面
         setTimeout(() => {
           uni.navigateTo({
             url: `/pages/pickup/my-publish`
           })
         }, 1500)
       } catch (error) {
         uni.hideLoading()
         console.error('创建订单失败:', error)
         uni.showToast({ title: error.msg || '创建订单失败', icon: 'none' })
       }
     }
  }
}
</script>

<style scoped>
.pickup-create {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #F5F5F5;
}

.content {
  flex: 1;
  padding: 24rpx;
}

.section {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  margin-bottom: 24rpx;
}

/* 地址选择器 */
.address-selector {
  background: #F8F9FA;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  display: flex;
  align-items: center;
  gap: 16rpx;
  position: relative;
}

.address-content {
  flex: 1;
}

.address-header {
  display: flex;
  gap: 16rpx;
  align-items: center;
  margin-bottom: 12rpx;
  flex-wrap: wrap;
}

.receiver-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.receiver-phone {
  font-size: 26rpx;
  color: #666;
}

.selected-badge {
  background: linear-gradient(135deg, #4ECDC4, #44A08D);
  color: #fff;
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}

.address-detail {
  display: flex;
  gap: 8rpx;
  align-items: flex-start;
}

.address-icon {
  font-size: 24rpx;
}

.address-text {
  flex: 1;
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
}

.address-empty {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.empty-icon {
  font-size: 36rpx;
}

.empty-text {
  font-size: 26rpx;
  color: #999;
}

.arrow-icon {
  font-size: 40rpx;
  color: #999;
}


.form-item {
  margin-bottom: 24rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-item input,
.form-item textarea {
  width: 100%;
  padding: 24rpx;
  background: #F8F9FA;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.form-item textarea {
  height: 120rpx;
}

.placeholder {
  color: #999;
}

.fee-input {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background: #F8F9FA;
  border-radius: 8rpx;
  padding: 24rpx;
}

.input-wrapper text {
  margin-right: 8rpx;
  color: #FF6B6B;
  font-weight: bold;
}

.input-wrapper input {
  flex: 1;
  width: 200rpx;
}

.fee-tip {
  background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
  border-radius: 12rpx;
  padding: 24rpx;
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.fee-tip .tip-icon {
  font-size: 36rpx;
}

.fee-tip .tip-text {
  flex: 1;
  font-size: 26rpx;
  color: #f57c00;
  line-height: 1.5;
}

.footer {
  padding: 24rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #4ECDC4, #44A08D);
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 44rpx;
  border: none;
}

/* 代取服务样式 */
.express-upload-section,
.other-service-upload {
  margin-bottom: 24rpx;
}
</style>

